//
//  FoodVC.m
//  爱寻找
//
//  Created by qianfeng0 on 16/6/23.
//  Copyright © 2016年 王超. All rights reserved.
//

#import "FoodVC.h"
#import "CHHTTPSessionRequset.h"
#import "Helper.h"
#import "FoodModel.h"
#import <MJRefresh.h>
#import "FoodCell.h"
#import "VideoPlayViewController.h"
#import "FunCollectionManager.h"
@interface FoodVC ()<favBtnDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSInteger _page;
    NSIndexPath *_index;
    UIButton *aBtn;
}
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation FoodVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.tabBarItem.selectedImage = [[UIImage imageNamed:@"iconfont-meishi-2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self getData];
    [self createUI];
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)createUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getData];
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"FoodCell" bundle:nil] forCellReuseIdentifier:@"FoodCell"];
    [self.view addSubview:self.tableView];
}

- (void)getData {
    CHHTTPSessionRequset *manager = [CHHTTPSessionRequset sharedManager];
    NSString *url = [NSString stringWithFormat:HeaderPage,_page];
    [manager GET:url pramas:nil success:^(id responseObject) {
//        NSLog(@"%@",responseObject);
        NSArray *data = responseObject[@"data"][@"data"];
        NSLog(@"%@",data);
        NSError *error = nil;
        NSMutableArray *foods = [FoodModel arrayOfModelsFromDictionaries:data error:&error];
        if (error) {
            NSLog(@"%@",error);
        } else {
            if (_page == 1) {
                self.dataSource = foods;
            } else {
                [self.dataSource addObjectsFromArray:foods];
            }
            
            [self.tableView reloadData];
        }
        [self endRefreshWith:_page];
    } failure:^(NSError *error) {
        [self endRefreshWith:_page];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 自定义的代理方法
- (void)btnClick:(UIButton *)btn and:(NSIndexPath *)indexPath{
    if (aBtn.frame.size.height>0) {
        [UIView animateWithDuration:1 animations:^{
            CGRect rect = aBtn.frame;
            rect.size.height = 0;
            aBtn.frame = rect;
            [aBtn removeFromSuperview];
        }];
        return;
    }
    _index = indexPath;
    aBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    aBtn.frame = CGRectMake(btn.frame.origin.x-15, 21 + btn.frame.origin.y, btn.frame.size.width+30, 0);
    aBtn.layer.borderWidth = 1;
    aBtn.layer.cornerRadius = 4;
    aBtn.layer.masksToBounds = YES;
    aBtn.backgroundColor = [UIColor whiteColor];
    aBtn.layer.borderColor = [UIColor grayColor].CGColor;
    FunCollectionManager *manager = [FunCollectionManager shareManager];
    if ([manager favIsExist:self.dataSource[indexPath.row]]) {
        [aBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
    } else {
        [aBtn setTitle:@"收藏" forState:UIControlStateNormal];
    }
    [aBtn addTarget:self action:@selector(btnHandle:) forControlEvents:UIControlEventTouchUpInside];
    [btn.superview addSubview:aBtn];
    [UIView animateWithDuration:0.1 animations:^{
        CGRect rect = aBtn.frame;
        rect.size.height = 30;
        aBtn.frame = rect;
    }];
}

#pragma mark - btn的点击方法
- (void)btnHandle:(UIButton *)btn {
    [UIView animateWithDuration:1 animations:^{
        CGRect rect = btn.frame;
        rect.size.height = 0;
        btn.frame = rect;
        [btn removeFromSuperview];
    }];
    FunCollectionManager *manager = [FunCollectionManager shareManager];
    if ([btn.currentTitle isEqualToString:@"收藏"]) {
        NSData *data = [self.dataSource[_index.row] toJSONData];
        if ([manager insertIntoFavWith:[self.dataSource[_index.row] dishes_id] and:data]) {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"收藏成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [view show];
        } else {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"收藏失败,请重试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [view show];
        }
    } else {
        if ([manager deleteFormFavBy:[self.dataSource[_index.row] dishes_id]]) {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"取消收藏成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [view show];
        } else {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"取消收藏失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [view show];
        }
    }
}

#pragma mark - 结束刷新的方法
- (void)endRefreshWith:(NSInteger)page {
    if (page == 1) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 145;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FoodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FoodCell"];
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FoodModel *model = self.dataSource[indexPath.row];
    VideoPlayViewController *videoVC = [[VideoPlayViewController alloc] init];
    AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:model.video]];
    videoVC.player = player;
    [self presentViewController:videoVC animated:YES completion:nil];
}

@end
